package com.example.test15_1;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements Runnable {

    private Thread thread;//声明线程对象
    int i ;//循环变量

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 开始 按钮监听事件
        Button startB = (Button) findViewById(R.id.start);
        startB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                i = 0;
                thread = new Thread(MainActivity.this);//创建一个线程
                thread.start();//开启线程
            }
        });

        // 停止 按钮监听事件
        Button stopB = (Button) findViewById(R.id.stop);
        stopB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (thread !=null){
                    thread.interrupt();//中断线程
                    thread = null;
                }
                Log.i("提示 : ","中断线程");
            }
        });
    }
    @Override
    public void run(){
        while(!Thread.currentThread().isInterrupted()){
            i++;
            Log.i("循环变量：",String.valueOf(i));
        }
    }
    @Override
    protected void onDestroy(){
        if (thread !=null){
            thread.interrupt();
            thread = null;
        }
        super.onDestroy();//中断线程
    }
}